package com.lengyu.vxminiprogram.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lengyu.vxminiprogram.common.AuthUtil;
import com.lengyu.vxminiprogram.common.CommonUtils;
import com.lengyu.vxminiprogram.dto.SecretRealmDto;
import com.lengyu.vxminiprogram.entity.SecretRealm;
import com.lengyu.vxminiprogram.entity.WowAffixDic;
import com.lengyu.vxminiprogram.entity.WowSpecializationDic;
import com.lengyu.vxminiprogram.mapper.SecretRealmMapper;
import com.lengyu.vxminiprogram.service.ISecretRealmService;
import com.lengyu.vxminiprogram.service.IWowAffixDicService;
import com.lengyu.vxminiprogram.service.IWowSpecializationDicService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TimeZone;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liuyu
 * @since 2024-12-10
 */
@Service
public class SecretRealmServiceImpl extends ServiceImpl<SecretRealmMapper, SecretRealm> implements ISecretRealmService {
    private final static Logger logger = LoggerFactory.getLogger(SecretRealmServiceImpl.class);

    @Autowired
    IWowAffixDicService wowAffixDicService;

    @Autowired
    IWowSpecializationDicService wowSpecializationDicService;

    @Override
    public String transferDataLine(String line, List<SecretRealmDto> realmList) {
        try{

            if(line.contains("CHALLENGE_MODE_START")){
                transferRealmStart(line,realmList);
            }
            else if(line.contains("CHALLENGE_MODE_END")){
                if(!realmList.get(realmList.size() - 1).isAnalyseSuccessFlag()){
                    transferRealmEnd(line,realmList);
                }

            }

            else if(line.contains("SPELL_SUMMON")){
                if(realmList.size() > 0){
                    if(!realmList.get(realmList.size() - 1).isAnalyseSuccessFlag()){
                        transferSPELL_SUMMON(line, realmList);
                    }
                }

            }
            else if(line.contains("SPELL_DAMAGE")){
                if(realmList.size() > 0){
                    if(!realmList.get(realmList.size() - 1).isAnalyseSuccessFlag()){
                        transferSpellDamage(line, realmList);
                    }
                }

            }
            else if(line.contains("SPELL_PERIODIC_DAMAGE")){
                if(realmList.size() > 0){
                    if(!realmList.get(realmList.size() - 1).isAnalyseSuccessFlag()){
                        transferSPELL_PERIODIC_DAMAGE(line, realmList);
                    }
                }
            }
            else if(line.contains("SWING_DAMAGE_LANDED")){
                if(realmList.size() > 0){
                    if(!realmList.get(realmList.size() - 1).isAnalyseSuccessFlag()){
                        transferSwingDamage(line, realmList);
                    }
                }

            }
            else if(line.contains("SPELL_HEAL")){
                if(realmList.size() > 0){
                    if(!realmList.get(realmList.size() - 1).isAnalyseSuccessFlag()){
                        transferSpellHealOrPERIODIC_HEAL(line, realmList);
                    }
                }

            }
            else if(line.contains("SPELL_PERIODIC_HEAL")){
                if(realmList.size() > 0){
                    if(!realmList.get(realmList.size() - 1).isAnalyseSuccessFlag()){
                        transferSpellHealOrPERIODIC_HEAL(line, realmList);
                    }
                }

            }
            else if(line.contains("SPELL_HEAL_ABSORBED")){
                if(realmList.size() > 0){
                    if(!realmList.get(realmList.size() - 1).isAnalyseSuccessFlag()){
                        transferSPELL_HEAL_ABSORBED(line, realmList);
                    }
                }
            }
            else if(line.contains("SPELL_INTERRUPT")){
                if(realmList.size() > 0){
                    if(!realmList.get(realmList.size() - 1).isAnalyseSuccessFlag()){
                        transferInterrupt(line, realmList);
                    }
                }
            }
            else if(line.contains("SPELL_AURA_APPLIED")){
                if(realmList.size() > 0){
                    if(!realmList.get(realmList.size() - 1).isAnalyseSuccessFlag()){
                        transferSPELL_AURA_APPLIED(line, realmList);
                    }
                }
            }
            else if(line.contains("UNIT_DIED")){
                if(realmList.size() > 0){
                    if(!realmList.get(realmList.size() - 1).isAnalyseSuccessFlag()){
                        transferDied(line, realmList);
                    }
                }
            }

            else if(line.contains("COMBATANT_INFO")){
                    transferComBatAnt(line,realmList);

            }
        }
        catch(Exception ex){
            logger.info(line);
            logger.error("error",ex);
        }

        return null;
    }

    private void transferSPELL_AURA_APPLIED(String line, List<SecretRealmDto> realmList) {
        String time = line.split("  ")[0];
        String data=line.split("  ")[1];
        String[] params = data.split(",");

        String skillName = params[10];
        if(skillName.contains("野兽顺劈")){

            String userId = params[1];
            String petId = params[5];
            String petName = params[6];
            if(userId.startsWith("Player")){
                if(realmList != null && realmList.size() > 0){
                    JSONArray characterArray = JSONArray.parseArray(realmList.get(realmList.size() - 1).getCharacters());
                    if(characterArray != null && characterArray.size() > 0){
                        for(int i=0;i<characterArray.size();i++){
                            if(characterArray.getJSONObject(i).getString("id").equals(userId)){
                                if(!characterArray.getJSONObject(i).containsKey("petId") || !characterArray.getJSONObject(i).getString("petId").contains(petId)){
                                    characterArray.getJSONObject(i).put("petId",characterArray.getJSONObject(i).getString("petId") + ","+ petId);

                                }
                                if(!characterArray.getJSONObject(i).containsKey("petName") || !characterArray.getJSONObject(i).getString("petName").contains(petName)){
                                    characterArray.getJSONObject(i).put("petName",characterArray.getJSONObject(i).getString("petName") + "," + petName);
                                }
                                realmList.get(realmList.size() - 1).setCharacters(characterArray.toJSONString());
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    private void transferSPELL_HEAL_ABSORBED(String line, List<SecretRealmDto> realmList) {
        String time = line.split("  ")[0];
        String data=line.split("  ")[1];
        String[] params = data.split(",");
        String userName = params[13].replace("\"","").replace("-TW","");
        String userId = params[12];
        String skillName = params[17];
        long heal = Long.parseLong(params[19]);
//        logger.info("line:" + line);
//        logger.info("skillName:"+skillName +" amount: " + heal);
        calcCommon(userId,userName,heal,realmList,"ABSORBED",skillName);
    }

    private void transferComBatAnt(String line, List<SecretRealmDto> realmList) {
        String time = line.split("  ")[0];
        String data=line.split("  ")[1];
        String[] params = data.split(",");
        String[] paramArray = data.split("\\[");
        String[] paramArray1s = paramArray[0].split(",");
        String tianfuId = paramArray1s[paramArray1s.length - 1];
        logger.info("天赋代码:" + tianfuId);
        String characterId = paramArray1s[1];
        WowSpecializationDic wowSpecializationDic = wowSpecializationDicService.getById(tianfuId);
        String career = "战士";
        String gift = "武器";
        String position="输出";
        if(wowSpecializationDic != null){
            career =wowSpecializationDic.getCareer();
            gift = wowSpecializationDic.getGift();
            position = wowSpecializationDic.getPosition();
        }
        logger.info("角色ID：" + characterId);
        if(realmList != null && realmList.size() > 0){
            JSONArray characterArray = JSONArray.parseArray(realmList.get(realmList.size() - 1).getCharacters());
            boolean hasFlag = false;
            if(characterArray != null && characterArray.size() > 0){
                for(int i=0;i<characterArray.size();i++){
                    if(characterArray.getJSONObject(i).getString("id").equals(characterId)){
                        hasFlag = true;
                        break;
                    }
                }
                if(!hasFlag){
                    JSONObject json = new JSONObject();
                    json.put("id",characterId);
                    json.put("career",career);
                    json.put("gift",gift);
                    json.put("position",position);
                    characterArray.add(json);
                }
                realmList.get(realmList.size() - 1).setCharacters(characterArray.toJSONString());
            }
            else{
                characterArray = new JSONArray();
                JSONObject json = new JSONObject();
                json.put("id",characterId);
                json.put("career",career);
                json.put("gift",gift);
                json.put("position",position);
                characterArray.add(json);
                realmList.get(realmList.size() - 1).setCharacters(characterArray.toJSONString());
            }
        }
    }

    private void transferSpellDamage(String line, List<SecretRealmDto> realmList) {
        String time = line.split("  ")[0];
        String data=line.split("  ")[1];
        String[] params = data.split(",");
        String userName = params[2].replace("\"","").replace("-TW","");
        String userId = params[1];
        long damageAmount = Long.parseLong(params[31]);
        calcCommon(userId,userName,damageAmount,realmList,"damage");
    }
    private void transferSpellHealOrPERIODIC_HEAL(String line, List<SecretRealmDto> realmList) {
        String time = line.split("  ")[0];
        String data=line.split("  ")[1];
        String[] params = data.split(",");
        String userName = params[2].replace("\"","").replace("-TW","");
        String userId = params[1];
        String skillName = params[10];
        long allheal = Long.parseLong(params[31]);

        long overheal = Long.parseLong(params[33]);
        long heal = allheal-overheal;
        logger.info("line:" + line);
//        logger.info("skillName:"+skillName +" amount: " + heal);
        calcCommon(userId,userName,heal,realmList,"heal",skillName);
        calcCommon(userId,userName,overheal,realmList,"overheal",skillName);
        calcCommon(userId,userName,allheal,realmList,"allheal",skillName);
    }

    private void transferInterrupt(String line, List<SecretRealmDto> realmList) {
        String time = line.split("  ")[0];
        String data=line.split("  ")[1];
        String[] params = data.split(",");
        String userName = params[2].replace("\"","").replace("-TW","");
        String userId = params[1];
        calcCommon(userId,userName,1L,realmList,"interrupt");
    }
    private void transferDied(String line, List<SecretRealmDto> realmList) {
        String time = line.split("  ")[0];
        String data=line.split("  ")[1];
        String[] params = data.split(",");
        String userName = params[6].replace("\"","").replace("-TW","");
        String userId = params[5];
        //1代表假死 0才是真死
        String deathFlag = params[9];
        if(deathFlag.equals("0")){
            calcCommon(userId,userName,1L,realmList,"died");
        }

    }


    private void transferSPELL_PERIODIC_DAMAGE(String line, List<SecretRealmDto> realmList) {
        String time = line.split("  ")[0];
        String data=line.split("  ")[1];
        String[] params = data.split(",");
        String userName = params[2].replace("\"","").replace("-TW","");
        String userId = params[1];
        long damageAmount = Long.parseLong(params[31]);
        calcCommon(userId,userName,damageAmount,realmList,"damage");
    }

    private void calcCommon(String userId,String userName ,long amount,List<SecretRealmDto> realmList,String type){
        calcCommon(userId,userName,amount,realmList,type,"");
    }

    private void calcCommon(String userId,String userName ,long amount,List<SecretRealmDto> realmList,String type,String skillName){
        if(userId.startsWith("Player")){
            if(realmList != null && realmList.size() > 0){
                JSONArray characterArray = JSONArray.parseArray(realmList.get(realmList.size() - 1).getCharacters());
                if(characterArray != null && characterArray.size() > 0){
                    for(int i=0;i<characterArray.size();i++){
                        if(characterArray.getJSONObject(i).getString("id").equals(userId)){
                            if(!characterArray.getJSONObject(i).containsKey("name")){
                                characterArray.getJSONObject(i).put("name",userName);
                            }
                            if(type.equals(type)){
                                if(!characterArray.getJSONObject(i).containsKey(type)){
                                    characterArray.getJSONObject(i).put(type,amount);
                                }
                                else{
                                    characterArray.getJSONObject(i).put(type,characterArray.getJSONObject(i).getLong(type)+amount);
                                }
//                                if(!characterArray.getJSONObject(i).containsKey(type+"_"+skillName)){
//                                    characterArray.getJSONObject(i).put(type+"_"+skillName,amount);
//                                    characterArray.getJSONObject(i).put(type+"_"+skillName+"_count",1);
//                                }
//                                else{
//                                    characterArray.getJSONObject(i).put(type+"_"+skillName,characterArray.getJSONObject(i).getLong(type+"_"+skillName)+amount);
//                                    characterArray.getJSONObject(i).put(type+"_"+skillName+"_count",characterArray.getJSONObject(i).getLong(type+"_"+skillName+"_count")+1);
//                                }
                            }

                            realmList.get(realmList.size() - 1).setCharacters(characterArray.toJSONString());
                            break;
                        }
                    }
                }
            }
        }
        else {
            if(type.equals("damage")||type.equals("heal")||type.equals("interrupt")||type.equals("ABSORBED")){
                if(realmList != null && realmList.size() > 0){
                    JSONArray characterArray = JSONArray.parseArray(realmList.get(realmList.size() - 1).getCharacters());
                    if(characterArray != null && characterArray.size() > 0){
                        for(int i=0;i<characterArray.size();i++){
                            if(characterArray.getJSONObject(i).containsKey("petId") && characterArray.getJSONObject(i).getString("petId").contains(userId)){
                                if(!characterArray.getJSONObject(i).containsKey(type)){
                                    characterArray.getJSONObject(i).put(type,amount);
                                }
                                else{
                                    characterArray.getJSONObject(i).put(type,characterArray.getJSONObject(i).getLong(type)+amount);

                                }
//                                if(!characterArray.getJSONObject(i).containsKey(type+"_"+skillName)){
//                                    characterArray.getJSONObject(i).put(type+"_"+skillName,amount);
//                                    characterArray.getJSONObject(i).put(type+"_"+skillName+"_count",1);
//                                }
//                                else{
//                                    characterArray.getJSONObject(i).put(type+"_"+skillName,characterArray.getJSONObject(i).getLong(type+"_"+skillName)+amount);
//                                    characterArray.getJSONObject(i).put(type+"_"+skillName+"_count",characterArray.getJSONObject(i).getLong(type+"_"+skillName+"_count")+1);
//                                }
                                realmList.get(realmList.size() - 1).setCharacters(characterArray.toJSONString());
                                break;
                            }
                        }

                    }
                }
            }

        }
    }

    private void transferSPELL_SUMMON(String line, List<SecretRealmDto> realmList) {
        String time = line.split("  ")[0];
        String data=line.split("  ")[1];
        String[] params = data.split(",");
        String userName = params[2].replace("\"","").replace("-TW","");
        String UserId = params[1];
        String petId= params[5];
        String petName= params[6];
//        long damageAmount = Long.parseLong(params[31]);
//        logger.info("DOT伤害");
//        logger.info(line);
//        logger.info(String.valueOf(damageAmount));
        if(UserId.startsWith("Player")){
            if(realmList != null && realmList.size() > 0){
                JSONArray characterArray = JSONArray.parseArray(realmList.get(realmList.size() - 1).getCharacters());
                if(characterArray != null && characterArray.size() > 0){
                    for(int i=0;i<characterArray.size();i++){
                        if(characterArray.getJSONObject(i).getString("id").equals(UserId)){
                            if(!characterArray.getJSONObject(i).containsKey("petId") || !characterArray.getJSONObject(i).getString("petId").contains(petId)){
                                characterArray.getJSONObject(i).put("petId",characterArray.getJSONObject(i).getString("petId") + ","+ petId);

                            }
                            if(!characterArray.getJSONObject(i).containsKey("petName") || !characterArray.getJSONObject(i).getString("petName").contains(petName)){
                                characterArray.getJSONObject(i).put("petName",characterArray.getJSONObject(i).getString("petName") + "," + petName);
                            }
                            realmList.get(realmList.size() - 1).setCharacters(characterArray.toJSONString());
                            break;
                        }
                    }
                }
            }
        }
    }

    private void transferSwingDamage(String line, List<SecretRealmDto> realmList) {

        String time = line.split("  ")[0];
        String data=line.split("  ")[1];
        String[] params = data.split(",");
        String userName = params[2].replace("\"","").replace("-TW","");
        String userId = params[1];
        long damageAmount = Long.parseLong(params[28]);
//        logger.info("近战伤害");
//        logger.info(line);
//        logger.info(String.valueOf(damageAmount));
        calcCommon(userId,userName,damageAmount,realmList,"damage");

    }


    /**
     *
     * @return
     */
    private String transferRealmStart(String line,List<SecretRealmDto> realmList){
        //CHALLENGE_MODE_START: zoneName, instanceID, challengeModeID, keystoneLevel, [affixID, ...]
        //CHALLENGE_MODE_START,"Mists of Tirna Scithe",2290,375,11,[9,122,4,121]
        //12/11/2024 10:50:05.4878  CHALLENGE_MODE_START,"千丝之城",2669,502,9,[160,10,152]
        String time = line.split("  ")[0];
        String data=line.split("  ")[1];
        String[] params = data.split(",");
        String realmName=params[1].replace("\"","");
        String instanceID = params[2];
        String challengeModeID = params[3];
        String keystoneLevel = params[4];
        String affixIds = data.split("\\[")[1].split("]")[0];
        StringBuilder sb = new StringBuilder();
        sb.append("大秘境开始---时间：");
        sb.append(time);

        sb.append(" 大秘境名称：");
        sb.append(realmName);
        sb.append(" 大秘境层数：");
        sb.append(keystoneLevel);
        SecretRealmDto secretRealm = new SecretRealmDto();
        secretRealm.setUserId(AuthUtil.getCurrentJwtUser().getId());
        secretRealm.setName(realmName);
        secretRealm.setLevel(keystoneLevel);
        secretRealm.setAffixIds(affixIds);
        String[] affixIdArray =  affixIds.split(",");
        List<WowAffixDic> affixDicList = wowAffixDicService.listByIds(Arrays.asList(affixIdArray));
        if(affixDicList != null){
            List<String> affixNameList = new ArrayList<>();
            affixDicList.forEach(i->{
                affixNameList.add(i.getName());
            });
            secretRealm.setAffixIds(affixNameList.toString());
        }
        //12/11/2024 10:51:40.6088
        secretRealm.setRealmTime(CommonUtils.StringToDate(time,"MM/dd/yyyy HH:mm:ss.SSSS"));
        realmList.add(secretRealm);
        logger.info(sb.toString());
        return sb.toString();
    }

    /**
     *
     * @return
     */
    private String transferRealmEnd(String line,List<SecretRealmDto> realmList){
        //CHALLENGE_MODE_END: instanceID, success, keystoneLevel, totalTime
        //12/11/2024 10:50:05.4318  CHALLENGE_MODE_END,2669,0,0,0,0.000000,0.000000
        String time = line.split("  ")[0];
        String data=line.split("  ")[1];
        String[] params = data.split(",");
        String instanceID=params[1];
        String success = params[2];
        String keystoneLevel = params[3];
        String totalTime = params[4];

        StringBuilder sb = new StringBuilder();
        sb.append("大秘境结束---时间：");
        sb.append(time);
//        sb.append(" 大秘境层数：");
//        sb.append(keystoneLevel);
        sb.append(" 是否限时：");
        sb.append(success);
//        sb.append(" 实例ID：");
//        sb.append(instanceID);
        sb.append(" 总用时：");
        sb.append(totalTime);
        if(realmList != null && realmList.size() > 0){
            realmList.get(realmList.size() - 1).setDeadlineTime(CommonUtils.StringToDate(time,"MM/dd/yyyy HH:mm:ss.SSSS"));
            SecretRealmDto realm =  realmList.get(realmList.size() - 1);
            long time1 = realm.getDeadlineTime().getTime() - realm.getRealmTime().getTime()-TimeZone.getDefault().getRawOffset();
            realmList.get(realmList.size() - 1).setHours(CommonUtils.timeToString(time1,"HH:mm:ss"));
            realmList.get(realmList.size() - 1).setSuccessFlag(Integer.parseInt(success));
            JSONArray characterArray = JSONArray.parseArray(realmList.get(realmList.size() - 1).getCharacters());
            if(characterArray != null && characterArray.size() > 0) {
                for (int i = 0; i < characterArray.size(); i++) {
                    // 将long转换为BigDecimal
                    BigDecimal bigDecimalNumber = new BigDecimal(characterArray.getJSONObject(i).getLong("damage"));

                    // 除以1亿（100,000,000）
                    BigDecimal totalTimeTmp = new BigDecimal((realm.getDeadlineTime().getTime() - realm.getRealmTime().getTime())/1000);
                    BigDecimal result = bigDecimalNumber.divide(totalTimeTmp, 2, RoundingMode.HALF_UP);
                    characterArray.getJSONObject(i).put("dps", result);

                    if(characterArray.getJSONObject(i).containsKey("heal")){
                        // 将long转换为BigDecimal
                        BigDecimal bigHeal = new BigDecimal(characterArray.getJSONObject(i).getLong("heal"));

                        BigDecimal resultHeal = bigHeal.divide(totalTimeTmp, 2, RoundingMode.HALF_UP);
                        characterArray.getJSONObject(i).put("hps", resultHeal);
                    }

                    if(characterArray.getJSONObject(i).containsKey("overheal")) {
                        BigDecimal bigOverHeal = new BigDecimal(characterArray.getJSONObject(i).getLong("overheal"));

                        BigDecimal resultOverHeal = bigOverHeal.divide(totalTimeTmp, 2, RoundingMode.HALF_UP);
                        characterArray.getJSONObject(i).put("hps_over", resultOverHeal);
                    }

                    if(characterArray.getJSONObject(i).containsKey("allheal")) {
                        BigDecimal bigAllHeal = new BigDecimal(characterArray.getJSONObject(i).getLong("allheal"));

                        BigDecimal resultAllHeal = bigAllHeal.divide(totalTimeTmp, 2, RoundingMode.HALF_UP);
                        characterArray.getJSONObject(i).put("hps_all", resultAllHeal);
                    }
                    if(characterArray.getJSONObject(i).containsKey("ABSORBED")) {
                        BigDecimal bigABSORBED = new BigDecimal(characterArray.getJSONObject(i).getLong("ABSORBED"));

                        BigDecimal resultABSORBED = bigABSORBED.divide(totalTimeTmp, 2, RoundingMode.HALF_UP);
                        characterArray.getJSONObject(i).put("ABSORBED", resultABSORBED);
                    }

                    characterArray.getJSONObject(i).put("petId", "");
                }
                realmList.get(realmList.size() - 1).setCharacters(characterArray.toJSONString());
                realmList.get(realmList.size() - 1).setAnalyseSuccessFlag(true);
            }
        }
        logger.info(sb.toString());
        return sb.toString();
    }
}
